package com.yanqu.road.server.manger.activity.rankunionwar;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarDivisionConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarFloorConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarTimeConfig;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.cricket.CricketData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.manor.FishData;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.player.UserVehicle;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.activity.RankUnionWarBusiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.RankUnionWarProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.rankunionwar.RankUnionWarModule;
import com.yanqu.road.server.gameplayer.module.cricket.CricketMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.VehicleMgr;
import com.yanqu.road.server.manger.manor.FishPondMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RankUnionWarMgr extends TempMgr {

    private static RandomHelper randomHelper = new RandomHelper();

    private static RankUnionWarConfig config;

    private static boolean isGetUnionIdList = false;

    //参加的商会总和，用来判断能不能进出商会
    public static Map<String,Boolean> unionIdMap = new ConcurrentHashMap<>();

    public static Map<Integer,List<Long>> sceneUserIdMap = new ConcurrentHashMap<>();

    public static Map<Long,List<Integer>> needUpdateUserPatronsMap = new ConcurrentHashMap<>();

    public static RandomHelper getRandomHelper() {
        return randomHelper;
    }

    public static void setRandomHelper(RandomHelper randomHelper) {
        RankUnionWarMgr.randomHelper = randomHelper;
    }

    public static ActivityInfo getActivity() {
        if(config != null){
            return config.getActivityInfo();
        }
        return null;
    }

    public static int getActivityId() {
        if(config != null && config.getActivityInfo() != null){
            return config.getActivityInfo().getActivityId();
        }
        return 0;
    }

    //哪个轮次的备战期，不是备战期也返回0
    public static int getReadyTurn() {
        if(config == null){
            return 0;
        }
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(System.currentTimeMillis());
        if(timeConfig != null){
            if(System.currentTimeMillis() < timeConfig.getStartTime()){
                return timeConfig.getSession();
            }
        }
        return 0;
    }

    public static RankUnionWarConfig getConfig() {
        return config;
    }

    public static void addUserScene(int gameNo,long userId){
        synchronized (sceneUserIdMap){
            if(!sceneUserIdMap.containsKey(gameNo)){
                sceneUserIdMap.put(gameNo,new ArrayList<>());
            }
            if(!sceneUserIdMap.get(gameNo).contains(userId)){
                sceneUserIdMap.get(gameNo).add(userId);
            }
        }
    }

    public static void removeUserScene(int gameNo,long userId){
        if(sceneUserIdMap.containsKey(gameNo)){
            sceneUserIdMap.get(gameNo).remove(userId);
        }
    }

    public static Map<Integer,List<Long>> getUserSceneMap(){
        return new ConcurrentHashMap<>(sceneUserIdMap);
    }

    //所有门客一起拉上去，一会要全部门客一会又要一部分门客
    private static Map<Integer,Map<Integer,UserPatrons>> getOccPatronsMap(Map<Integer, UserPatrons> userPatronsMap){
        Map<Integer,Map<Integer,UserPatrons>> retMap = new ConcurrentHashMap<>();
        for(UserPatrons userPatrons : userPatronsMap.values()){
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(userPatrons.getPatronsId());
            if(!retMap.containsKey(patronsInfo.getOccupation())){
                retMap.put(patronsInfo.getOccupation(),new ConcurrentHashMap<>());
            }
            retMap.get(patronsInfo.getOccupation()).put(userPatrons.getPatronsId(),userPatrons);
        }
        return retMap;
    }

    //获取每个职业前多少的玩家
    private static Map<Integer,Map<Integer,UserPatrons>> getTopOccPatronsMap(Map<Integer, UserPatrons> userPatronsMap){
        Map<Integer,Map<Integer,UserPatrons>> retMap = new ConcurrentHashMap<>();
        Map<Integer,List<UserPatrons>> allOccPatronsMap = new ConcurrentHashMap<>();
        for(UserPatrons userPatrons : userPatronsMap.values()){
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(userPatrons.getPatronsId());
            if(!allOccPatronsMap.containsKey(patronsInfo.getOccupation())){
                allOccPatronsMap.put(patronsInfo.getOccupation(),new ArrayList<>());
                retMap.put(patronsInfo.getOccupation(),new ConcurrentHashMap<>());
            }
            allOccPatronsMap.get(patronsInfo.getOccupation()).add(userPatrons);
        }
        for(int occId : allOccPatronsMap.keySet()){
            List<UserPatrons> patronsList = allOccPatronsMap.get(occId);
            patronsList.sort(new PatronsQualification());
            for(int i = 0; i < config.getMaxPatrons();i++){
                if(i >= patronsList.size()){
                    break;
                }
                UserPatrons userPatrons = allOccPatronsMap.get(occId).get(i);
                retMap.get(occId).put(userPatrons.getPatronsId(),userPatrons);
            }
        }
        return retMap;
    }

    public static boolean canJoinUnion(String unionUid) {
        /*if(isActivityIn()){
            if(unionIdList.contains(unionUid)){
                return false;
            }
        }*/
        return true;
    }

    public static boolean canKickUnion(String unionUid) {
        /*if(isActivityIn()){
            if(unionIdList.contains(unionUid)){
                return false;
            }
        }*/
        return true;
    }

    public static boolean canDelUnion(String unionUid) {
        if(isActivityIn()){
            //数据还没来不能解散商会
            if(unionIdMap.size() == 0 || unionIdMap.containsKey(unionUid)){
                return false;
            }
        }
        return true;
    }

    private static boolean isActivityIn(){
        long nowTime = System.currentTimeMillis()/1000;
        if(getActivity() == null || nowTime < getActivity().getBeginTime() || nowTime > getActivity().getEndTime()){
            return false;
        }
        return true;
    }

    public static void patronsAbilityChange(UserInfo userInfo, List<UserPatrons> patronsList) {
        if(!isActivityIn()){
            return;
        }
        if(!unionIdMap.containsKey(userInfo.getUnionUid())){
            return;
        }
        synchronized (needUpdateUserPatronsMap){
            if(!needUpdateUserPatronsMap.containsKey(userInfo.getUserId())){
                needUpdateUserPatronsMap.put(userInfo.getUserId(),new ArrayList<>());
            }
        }
        List<Integer> patronsIdList = needUpdateUserPatronsMap.get(userInfo.getUserId());
        synchronized (patronsIdList){
            for(UserPatrons patrons : patronsList){
                if(!patronsIdList.contains(patrons.getPatronsId())){
                    patronsIdList.add(patrons.getPatronsId());
                }
            }
        }
    }

    public static void timerTask() {
        if(!isGetUnionIdList){
            sendGetUnionIdList();
        }
        updateUserPatronsMap();
    }

    public static void updateUserPatronsMap(){
        if(!isActivityIn() || getReadyTurn() == 0){
            return;
        }
        Map<Long,List<Integer>> tempNeedUpdateUserPatronsMap = new ConcurrentHashMap<>();
        if(needUpdateUserPatronsMap.size() > 0){
            synchronized (needUpdateUserPatronsMap){
                tempNeedUpdateUserPatronsMap = new ConcurrentHashMap<>(needUpdateUserPatronsMap);
                needUpdateUserPatronsMap.clear();
            }
        }

        RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
        respMsg.setActivityId(getActivityId());
        respMsg.setTurn(getReadyTurn());
        int sendIndex = 0;
        for(long userId : tempNeedUpdateUserPatronsMap.keySet()){
            UserInfo userInfo = UserMgr.getUserInfo(userId);
            if(!unionIdMap.containsKey(userInfo.getUnionUid())){
                continue;
            }
            RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.Builder userMsg = RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.newBuilder();
            userMsg.setUnionUid(userInfo.getUnionUid());
            userMsg.setUserId(userId);
            Map<Integer, UserPatrons> userPatronsMap = PatronsMgr.getUserPatronsMap(userId);
            Map<String, UserVehicle> userVehicleMap = VehicleMgr.getUserVehicleMap(userId);
            Map<Integer, FishData> userFishMap = FishPondMgr.getUserFishMap(userId);
            Map<Integer, CricketData> userCricketMap = CricketMgr.getUserCricketMap(userId);
            for(Integer patronsId : tempNeedUpdateUserPatronsMap.get(userId)){
                RankUnionWarProto.CrossRankUnionWarPatronsMsg.Builder patronsMsg = RankUnionWarProto.CrossRankUnionWarPatronsMsg.newBuilder();
                UserPatrons userPatrons = userPatronsMap.get(patronsId);
                if(userPatrons != null){
                    patronsMsg.setPatronsId(userPatrons.getPatronsId());
                    patronsMsg.setEarnSpeed(userPatrons.getAbility().toString());
                    patronsMsg.setSkinId(userPatrons.getSkinId());
                    patronsMsg.setPromotionId(userPatrons.getShowPromotionId());
                    UserVehicle userVehicle = getUserVehicle(userVehicleMap,userPatrons.getPatronsId());
                    patronsMsg.setVehicleUid(userVehicle == null?"":userVehicle.getVehicleUid());
                    FishData fishData = getUserFish(userFishMap,userPatrons.getPatronsId());
                    patronsMsg.setFishId(fishData == null?0:fishData.getFishId());
                    CricketData cricketData = RankUnionWarMgr.getUserCricket(userCricketMap,userPatrons.getPatronsId());
                    patronsMsg.setCricketId(cricketData == null?0:cricketData.getCricketId());
                    userMsg.addPatrons(patronsMsg);
                }
            }
            respMsg.addUsers(userMsg);
            sendIndex++;
            if(sendIndex >= 5){
                RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder tempMsg = respMsg;
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_SET_PATRONS_INFO, tempMsg);
                GamePlayerMgr.sendPacket(0, pbMsg);
                sendIndex = 0;
                respMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
                respMsg.setActivityId(getActivityId());
                respMsg.setTurn(getReadyTurn());
            }
        }
        if(respMsg.getUsersCount() > 0){
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_SET_PATRONS_INFO, respMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    public static boolean isUserCanBuyRmb(int activityId, long userId) {
        if(!isActivityIn()){
            return false;
        }
        if(activityId != getActivityId()){
            return false;
        }

        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if(userInfo != null && unionIdMap.containsKey(userInfo.getUnionUid()) && !unionIdMap.get(userInfo.getUnionUid())){
            return true;
        }
        return false;
    }


    //大到小
    static class PatronsQualification implements Comparator<UserPatrons> {
        @Override
        public int compare(UserPatrons o1, UserPatrons o2) {
            if (o1.getTotalQualification() == o2.getTotalQualification()) {
                return 0;
            }
            if (o1.getTotalQualification() > o2.getTotalQualification()) {
                return -1;
            }
            return 1;
        }
    }

    //加入商会向告诉活动判断玩家有没有资格喝加入参加门客
    public static void joinUnionSendCross(String unionId,List<CrossUnionMember> memberList){
        if(!unionIdMap.containsKey(unionId)){
            return;
        }
        long nowTime = System.currentTimeMillis()/1000;
        if(config != null && config.getActivityInfo() != null && nowTime > config.getActivityInfo().getBeginTime() && nowTime < config.getActivityInfo().getEndTime()){
            RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
            syncMsg.setActivityId(config.getActivityInfo().getActivityId());
            syncMsg.setTurn(0);
            for(CrossUnionMember member : memberList){
                if(!unionIdMap.containsKey(member.getUnionUid()))continue;
                RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.Builder userMsg = RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.newBuilder();
                UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(member.getUserId(),member.getServerId());
                if(userBaseInfo == null)continue;
                /*RankUnionWarProto.RankUnionWarUnionMemberMsg.Builder memberMsg = RankUnionWarProto.RankUnionWarUnionMemberMsg.newBuilder();
                memberMsg.setServerId(member.getServerId());
                memberMsg.setUserId(member.getUserId());
                memberMsg.setEarnSpeed(userBaseInfo.getEarnSpeed().toString());
                memberMsg.setPosition(member.getPosition());
                userMsg.setMemberData(memberMsg);*/
                userMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                userMsg.setUnionUid(member.getUnionUid());
                userMsg.setUserId(member.getUserId());
                Map<Integer, UserPatrons> userPatronsMap = PatronsMgr.getUserPatronsMap(member.getUserId());
                Map<String, UserVehicle> userVehicleMap = VehicleMgr.getUserVehicleMap(member.getUserId());
                Map<Integer, FishData> userFishMap = FishPondMgr.getUserFishMap(member.getUserId());
                for(UserPatrons userPatrons : userPatronsMap.values()){
                    RankUnionWarProto.CrossRankUnionWarPatronsMsg.Builder patronsMsg = RankUnionWarProto.CrossRankUnionWarPatronsMsg.newBuilder();
                    patronsMsg.setPatronsId(userPatrons.getPatronsId());
                    patronsMsg.setEarnSpeed(userPatrons.getAbility().toString());
                    patronsMsg.setSkinId(userPatrons.getSkinId());
                    patronsMsg.setPromotionId(userPatrons.getShowPromotionId());
                    UserVehicle userVehicle = getUserVehicle(userVehicleMap,userPatrons.getPatronsId());
                    patronsMsg.setVehicleUid(userVehicle == null?"":userVehicle.getVehicleUid());
                    FishData fishData = getUserFish(userFishMap,userPatrons.getPatronsId());
                    patronsMsg.setFishId(fishData == null?0:fishData.getFishId());

                    userMsg.addPatrons(patronsMsg);
                }
                syncMsg.addUsers(userMsg);
            }

            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_JOIN_UNION, syncMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    public static boolean isMatchUnion(String unionId){
        return unionIdMap.containsKey(unionId);
    }

    //玩家退出商会，游戏备战期退出要给他
    public static void quitUnionSendCross(String unionId ,List<Long> userIdList){
        if(!unionIdMap.containsKey(unionId)){
            return;
        }
        long nowTime = System.currentTimeMillis()/1000;
        if(config != null && config.getActivityInfo() != null && nowTime > config.getActivityInfo().getBeginTime() && nowTime < config.getActivityInfo().getEndTime()){
            RankUnionWarProto.CrossRankUnionWarQuitUnionSyncMsg.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarQuitUnionSyncMsg.newBuilder();
            syncMsg.setActivityId(config.getActivityInfo().getActivityId());
            for(long memberUserId : userIdList){
                RankUnionWarProto.CrossRankUnionWarQuitUnionMsg.Builder memberMsg = RankUnionWarProto.CrossRankUnionWarQuitUnionMsg.newBuilder();
                memberMsg.setUnionUid(unionId);
                memberMsg.setUserId(memberUserId);
                UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(memberUserId,GameServer.getInstance().getServerId());
                if(userBaseInfo != null){
                    memberMsg.setPlayerBaseData((PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo)));
                }
                syncMsg.addQuit(memberMsg);
            }

            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_QUIT_UNION, syncMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }


    public static void positionUnionSendCross(List<CrossUnionMember> memberList) {
        List<CrossUnionMember> needUpdateMemberList = new ArrayList<>();
        for(CrossUnionMember member : memberList){
            if(unionIdMap.containsKey(member.getUnionUid())){
                needUpdateMemberList.add(member);
            }
        }
        if(needUpdateMemberList.size() == 0){
            return;
        }
        long nowTime = System.currentTimeMillis()/1000;
        if(config != null && config.getActivityInfo() != null && nowTime > config.getActivityInfo().getBeginTime() && nowTime < config.getActivityInfo().getEndTime()){
            RankUnionWarProto.CrossRankUnionWarPositionUnionSyncMsg.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarPositionUnionSyncMsg.newBuilder();
            syncMsg.setActivityId(config.getActivityInfo().getActivityId());
            for(CrossUnionMember needMember : needUpdateMemberList){
                RankUnionWarProto.CrossRankUnionWarPositionUnionMsg.Builder positionMsg = RankUnionWarProto.CrossRankUnionWarPositionUnionMsg.newBuilder();
                positionMsg.setUnionUid(needMember.getUnionUid());
                positionMsg.setUserId(needMember.getUserId());
                positionMsg.setPosition(needMember.getPosition());
                syncMsg.addPosition(positionMsg);
            }

            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_POSITION_UNION, syncMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    public static UserVehicle getUserVehicle(Map<String, UserVehicle> userVehicleMap ,int patronsId){
        for(UserVehicle userVehicle : userVehicleMap.values()){
            if(userVehicle.getPatronsId() == patronsId){
                return userVehicle;
            }
        }
        return null;
    }

    public static FishData getUserFish(Map<Integer, FishData> userFishMap ,int patronsId){
        for(FishData fishData : userFishMap.values()){
            if(fishData.getEquipPatronsId() == patronsId){
                return fishData;
            }
        }
        return null;
    }

    public static CricketData getUserCricket(Map<Integer, CricketData> userCricketMap , int patronsId){
        for(CricketData cricketData : userCricketMap.values()){
            if(cricketData.getEquipPatronsId() == patronsId){
                return cricketData;
            }
        }
        return null;
    }

    //来拉门客上场
    public static void syncUserPatronsData(int activityId,int turn,Map<Long,List<Integer>> userIdPatronsIdMap,Map<Long,String> userUnionIdMap){
        //如果死人太多就会一直读库，集中一起读出来
        List<Long> outLineUserList = new ArrayList<>();
        for(long userId : userIdPatronsIdMap.keySet()){
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(null == player){
                outLineUserList.add(userId);
            }
        }
        Map<Long,Map<Integer, UserPatrons>> outlineUserPatronsMap = new ConcurrentHashMap<>();
        Map<Long,Map<String, UserVehicle>> outlineUserVehicleMap = new ConcurrentHashMap<>();
        Map<Long,Map<Integer, FishData>> outlineUserFishMap = new ConcurrentHashMap<>();
        Map<Long,Map<Integer, CricketData>> outlineUserCricketMap = new ConcurrentHashMap<>();
        if(outLineUserList.size() > 0){
            outlineUserPatronsMap = PatronsMgr.getSomeUserPatronsMap(outLineUserList);
            outlineUserVehicleMap = VehicleMgr.getSomeUserVehicleMap(outLineUserList);
            outlineUserFishMap = FishPondMgr.getSomeUserFishMap(outLineUserList);
            outlineUserCricketMap = CricketMgr.getSomeUserFishMap(outLineUserList);
        }

        RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
        respMsg.setActivityId(activityId);
        respMsg.setTurn(turn);
        //包太大了，分多次来吧
        int sendIndex = 0;
        for(long userId : userIdPatronsIdMap.keySet()){
            RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.Builder userMsg = RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg.newBuilder();
            userMsg.setUnionUid(userUnionIdMap.get(userId));
            userMsg.setUserId(userId);

            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            Map<Integer, UserPatrons> userPatronsMap = new ConcurrentHashMap<>();
            Map<String, UserVehicle> userVehicleMap = new ConcurrentHashMap<>();
            Map<Integer, FishData> userFishMap = new ConcurrentHashMap<>();
            Map<Integer, CricketData> userCricketMap = new ConcurrentHashMap<>();
            if(null != player){
                userPatronsMap = PatronsMgr.getUserPatronsMap(userId);
                userVehicleMap = VehicleMgr.getUserVehicleMap(userId);
                userFishMap = FishPondMgr.getUserFishMap(userId);
                userCricketMap = CricketMgr.getUserCricketMap(player.getUserId());
            }else {
                if(outlineUserPatronsMap.containsKey(userId)){
                    userPatronsMap = outlineUserPatronsMap.get(userId);
                }else{
                    userPatronsMap = PatronsMgr.getUserPatronsMap(userId);
                }

                if(outlineUserVehicleMap.containsKey(userId)){
                    userVehicleMap = outlineUserVehicleMap.get(userId);
                }else{
                    userVehicleMap = VehicleMgr.getUserVehicleMap(userId);
                }

                if(outlineUserFishMap.containsKey(userId)){
                    userFishMap = outlineUserFishMap.get(userId);
                }else{
                    userFishMap = FishPondMgr.getUserFishMap(userId);
                }
                if(outlineUserCricketMap.containsKey(userId)){
                    userCricketMap = outlineUserCricketMap.get(userId);
                }else{
                    userCricketMap = CricketMgr.getUserCricketMap(userId);
                }
            }

            if(userPatronsMap.size() == 0){
                getLogger().error("玩家{}的门客数据为空",userId);
            }
            //第一次来拉取前几名门客
            if(userIdPatronsIdMap.get(userId).size() == 0){
                Map<Integer,Map<Integer,UserPatrons>> retMap = getOccPatronsMap(userPatronsMap);
                for(Map<Integer,UserPatrons> paMap : retMap.values()){
                    for(UserPatrons userPatrons : paMap.values()){
                        RankUnionWarProto.CrossRankUnionWarPatronsMsg.Builder patronsMsg = RankUnionWarProto.CrossRankUnionWarPatronsMsg.newBuilder();
                        patronsMsg.setPatronsId(userPatrons.getPatronsId());
                        patronsMsg.setEarnSpeed(userPatrons.getAbility().toString());
                        patronsMsg.setSkinId(userPatrons.getSkinId());
                        patronsMsg.setPromotionId(userPatrons.getShowPromotionId());
                        UserVehicle userVehicle = getUserVehicle(userVehicleMap,userPatrons.getPatronsId());
                        patronsMsg.setVehicleUid(userVehicle == null?"":userVehicle.getVehicleUid());
                        FishData fishData = getUserFish(userFishMap,userPatrons.getPatronsId());
                        patronsMsg.setFishId(fishData == null?0:fishData.getFishId());
                        CricketData cricketData = RankUnionWarMgr.getUserCricket(userCricketMap,userPatrons.getPatronsId());
                        patronsMsg.setCricketId(cricketData == null?0:cricketData.getCricketId());
                        userMsg.addPatrons(patronsMsg);
                    }
                }
            }else{
                for(Integer patronsId : userIdPatronsIdMap.get(userId)){
                    RankUnionWarProto.CrossRankUnionWarPatronsMsg.Builder patronsMsg = RankUnionWarProto.CrossRankUnionWarPatronsMsg.newBuilder();
                    UserPatrons userPatrons = userPatronsMap.get(patronsId);
                    if(userPatrons != null){
                        patronsMsg.setPatronsId(userPatrons.getPatronsId());
                        patronsMsg.setEarnSpeed(userPatrons.getAbility().toString());
                        patronsMsg.setSkinId(userPatrons.getSkinId());
                        patronsMsg.setPromotionId(userPatrons.getShowPromotionId());
                        UserVehicle userVehicle = getUserVehicle(userVehicleMap,userPatrons.getPatronsId());
                        patronsMsg.setVehicleUid(userVehicle == null?"":userVehicle.getVehicleUid());
                        FishData fishData = getUserFish(userFishMap,userPatrons.getPatronsId());
                        patronsMsg.setFishId(fishData == null?0:fishData.getFishId());
                        CricketData cricketData = RankUnionWarMgr.getUserCricket(userCricketMap,userPatrons.getPatronsId());
                        patronsMsg.setCricketId(cricketData == null?0:cricketData.getCricketId());
                        userMsg.addPatrons(patronsMsg);
                    }
                }
            }
            respMsg.addUsers(userMsg);
            sendIndex++;
            if(sendIndex >= 100){
                RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.Builder tempRespMsg = respMsg;
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_SET_PATRONS_INFO, tempRespMsg);
                GamePlayerMgr.sendPacket(0, pbMsg);
                sendIndex = 0;
                respMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg.newBuilder();
                respMsg.setActivityId(activityId);
                respMsg.setTurn(turn);
            }
        }
        if(respMsg.getUsersCount() > 0){
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_SET_PATRONS_INFO, respMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    //随机鼓舞奖励
    public static String randomInspireReward(){
        String rewardStr = "";
        List<String> rewardList = config.getInspireRewardList();
        List<Integer> rewardWeightList = config.getInspireRewardWeightList();

        int totalWeight = 0;
        for (int weight : rewardWeightList) {
            totalWeight += weight;
        }
        int randomNum = randomHelper.next(0, totalWeight);
        for (int i = 0; i < rewardWeightList.size(); i++) {
            int value = rewardWeightList.get(i);
            if (randomNum < value) {
                rewardStr = rewardList.get(i);
                break;
            }
            randomNum -= value;
        }
        return rewardStr;
    }

    //捐献奖励
    public static String randomDonateReward(){
        String rewardStr = "";
        List<String> rewardList = config.getDonateRewardList();
        List<Integer> rewardWeightList = config.getDonateRewardWeightList();

        int totalWeight = 0;
        for (int weight : rewardWeightList) {
            totalWeight += weight;
        }
        int randomNum = randomHelper.next(0, totalWeight);
        for (int i = 0; i < rewardWeightList.size(); i++) {
            int value = rewardWeightList.get(i);
            if (randomNum < value) {
                rewardStr = rewardList.get(i);
                break;
            }
            randomNum -= value;
        }
        return rewardStr;
    }

    //捐献奖励
    public static String randomDonateReward(int donateNum){
        Property rewardProperty = new Property();
        for(int i = donateNum; i > 0; i--){
            rewardProperty.addProperty(PropertyHelper.parseStringToProperty(randomDonateReward()));
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }

    //随机一个大奖位置
    public static int randomBigRewardPosition(){
        return randomHelper.next(0,config.getBoxLength());
    }

    //宝库开启奖励
    public static String randomBoxReward(int floor){
        String rewardStr = "";
        Map<Integer, RankUnionWarFloorConfig> floorConfigMap = config.getFloorConfigMap();
        RankUnionWarFloorConfig floorConfig = floorConfigMap.get(floor);

        int totalWeight = 0;
        for (Integer weight : floorConfig.getRewardsWeighListt()) {
            totalWeight += weight;
        }
        int randomNum = randomHelper.next(0, totalWeight);
        for (int i = 0; i < floorConfig.getRewardsWeighListt().size(); i++) {
            int value = floorConfig.getRewardsWeighListt().get(i);
            if (randomNum < value) {
                rewardStr = floorConfig.getRewardsList().get(i);
                break;
            }
            randomNum -= value;
        }
        return rewardStr;
    }

    public static String randomBoxBigReward(int floor){
        Property reward = new Property();
        Map<Integer, RankUnionWarFloorConfig> floorConfigMap = config.getFloorConfigMap();
        RankUnionWarFloorConfig floorConfig = floorConfigMap.get(floor);
        reward = PropertyHelper.parseStringToProperty(floorConfig.getSpecialReward());
        if(floorConfig.getSpecialRewardsList() != null){
            int totalWeight = 0;
            for (Integer weight : floorConfig.getSpecialRewardsWeightList()) {
                totalWeight += weight;
            }
            int randomNum = randomHelper.next(0, totalWeight);
            for (int i = 0; i < floorConfig.getSpecialRewardsWeightList().size(); i++) {
                int value = floorConfig.getSpecialRewardsWeightList().get(i);
                if (randomNum < value) {
                    reward.addProperty(PropertyHelper.parseStringToProperty(floorConfig.getSpecialRewardsList().get(i)));
                    break;
                }
                randomNum -= value;
            }
        }

        return PropertyHelper.parsePropertyToString(reward);
    }



    public static String getFloorOpenCost(int floor) {
        return config.getFloorConfigMap().get(floor).getConsume();
    }


    private static void sendGetUnionIdList(){
        if(isActivityIn()){
            getLogger().info("巅峰活动{}区服{}发送拉取跨服比赛商会信息",getActivityId(),GameServer.getInstance().getServerId());
            RankUnionWarProto.CrossRankUnionWarGetUnionIdListReqMsg.Builder reqMsg = RankUnionWarProto.CrossRankUnionWarGetUnionIdListReqMsg.newBuilder();
            reqMsg.setActivityId(getActivityId());
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CROSS_RANKUNIONWAR_GET_UNIONID_LIST, reqMsg);
            GamePlayerMgr.sendPacket(0, pbMsg);
        }
    }

    public static void setUnionIdMap(Map<String,Boolean> crossUnionMap){
        if(isActivityIn()){
            getLogger().info("巅峰活动{}区服{}获得了跨服同步的商会id信息{}个商会",getActivityId(),GameServer.getInstance().getServerId(),crossUnionMap.size());
            isGetUnionIdList = true;
            for(String unionId : crossUnionMap.keySet()){
                unionIdMap.put(unionId,crossUnionMap.get(unionId));
            }
        }
    }

    public static void updateUnionIdMap(Map<String,Boolean> crossUnionMap){
        if(isActivityIn()){
            getLogger().info("巅峰活动{}区服{}获得了跨服同步的商会信息更新{}个商会",getActivityId(),GameServer.getInstance().getServerId(),crossUnionMap.size());
            for(String unionId : crossUnionMap.keySet()){
                if(unionIdMap.containsKey(unionId)){
                    unionIdMap.put(unionId,crossUnionMap.get(unionId));
                }
            }
        }
    }

    public static void setUnionIdList(List<String> crossUnionIdList){
        if(isActivityIn()){
            getLogger().info("巅峰活动{}区服{}获得了跨服同步的商会id信息{}个商会",getActivityId(),GameServer.getInstance().getServerId(),crossUnionIdList.size());
            isGetUnionIdList = true;
//            unionIdList = crossUnionIdList;
        }
    }

    //自定义每一轮重置购买
    public static void resetMallBuy(){

    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void reloadActivityData() {
        getLogger().info("reload RankUnionWar activity start");

        // 获取活动
        ActivityInfo tmpActivityInfo;
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.RankUnionWar.getValue());
        if (openActivityInfoList.size() <= 0) {
            //用是不是有活动判断是不是
            if(config != null){
                config.setActivityInfo(null);
            }
            getLogger().info("no RankUnionWar activity in show time");
            return;
        }
        tmpActivityInfo = openActivityInfoList.get(0);

        Map<Integer, RankUnionWarTimeConfig> tempTimeConfigMap = RankUnionWarBusiness.getTimeConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, RankUnionWarDivisionConfig> tempDivisionConfigMap = RankUnionWarBusiness.getDivisionConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, RankUnionWarFloorConfig> tempFloorConfigMap = RankUnionWarBusiness.getFloorConfigMap(tmpActivityInfo.getActivityId());

        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityInfo.getActivityId());
        RankUnionWarConfig tempConfig = new RankUnionWarConfig();
        tempConfig.setActivityInfo(tmpActivityInfo);
        tempConfig.initConfig(activityConfigMap,tempTimeConfigMap,tempDivisionConfigMap,tempFloorConfigMap);
        config = tempConfig;

        isGetUnionIdList = false;
        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(RankUnionWarModule.class).afterLogin();
        }
    }


}
